All files / vidly/routes customers.js

30.3% Statements 10/33
0% Branches 0/10
0% Functions 0/5
35.71% Lines 10/28
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 572x 2x 2x 2x   2x         2x                           2x                               2x               2x               2x
const {Customer, validate} = require('../models/customer'); 
const mongoose = require('mongoose');
const express = require('express');
const router = express.Router();
 
router.get('/', async (req, res) => {
  const customers = await Customer.find().sort('name');
  res.send(customers);
});
 
router.post('/', async (req, res) => {
  const { error } = validate(req.body); 
  if (error) return res.status(400).send(error.details[0].message);
 
  let customer = new Customer({ 
    name: req.body.name,
    isGold: req.body.isGold,
    phone: req.body.phone
  });
  customer = await customer.save();
  
  res.send(customer);
});
 
router.put('/:id', async (req, res) => {
  const { error } = validate(req.body); 
  if (error) return res.status(400).send(error.details[0].message);
 
  const customer = await Customer.findByIdAndUpdate(req.params.id,
    { 
      name: req.body.name,
      isGold: req.body.isGold,
      phone: req.body.phone
    }, { new: true });
 
  if (!customer) return res.status(404).send('The customer with the given ID was not found.');
  
  res.send(customer);
});
 
router.delete('/:id', async (req, res) => {
  const customer = await Customer.findByIdAndRemove(req.params.id);
 
  if (!customer) return res.status(404).send('The customer with the given ID was not found.');
 
  res.send(customer);
});
 
router.get('/:id', async (req, res) => {
  const customer = await Customer.findById(req.params.id);
 
  if (!customer) return res.status(404).send('The customer with the given ID was not found.');
 
  res.send(customer);
});
 
module.exports = router;